import akshare as ak
import pandas as pd
import time
import asyncio
import signal
import os, atexit
from threading import Timer
from server import Server
from flow_watcher import FlowWatcher
import os, sys
from common import utils

loop = asyncio.new_event_loop()

allStocks = {}

def get_one_stock(code, name):
    if (utils.isBadStock(code, name)):
        return None       

    if code not in allStocks:
        allStocks[code] = {}

    return allStocks[code]

def pull_once():
    start = time.time()
    flow = ak.stock_individual_fund_flow_rank(indicator="今日")
    flow = flow[flow['今日主力净流入-净占比'] != '-' ]
    flow = flow.sort_values(by="今日主力净流入-净占比", ascending=False)

    flowRank = []

    order = 0
    for index, row in flow.iterrows():
        code = row['代码']
        name = row['名称']
        sbig = row['今日超大单净流入-净额']
        sbig_p = row['今日超大单净流入-净占比']
        mbig = row['今日主力净流入-净额']
        mbig_p = row['今日主力净流入-净占比']

        if order < 10:
            if utils.isTypeB(code):
                continue

            flowRank.append({
                'code': code,
                'name': name,
                'price': row['最新价'],
                'up': row['今日涨跌幅'],
                'mbig': utils.formatNumber(mbig),
                'mbig_p': mbig_p,
                'sbig': utils.formatNumber(sbig),
                'sbig_p': sbig_p,
                })
            order += 1

        stock = get_one_stock(code, name)
        if (stock is None):
            continue

        if sbig == '-':
            stock['mbig'] = 'NA'
        else:
            stock['mbig'] = utils.formatNumber(mbig)

        if sbig == '-':
            stock['sbig'] = 'NA'
        else:
            stock['sbig'] = utils.formatNumber(sbig)

    spot = ak.stock_zh_a_spot_em()
    for index, row in spot.iterrows():
        code = row['代码']
        name = row['名称']

        stock = get_one_stock(code, name)
        if (stock is None):
            continue

        stock["code"] = code
        stock["price"] = row['最新价'],
        stock["close"] = row['昨收'],
        stock["volume"] = utils.formatNumber(row['成交量']),
        stock["qrr"] = row['量比'],
        stock["up"] = row['涨跌幅'],
        stock["time"] = utils.cur_time_short()

    loop.run_until_complete(wsServer.update(allStocks, flowRank))
    end = time.time()
    print('%s 更新耗时 %.1f 秒' %(utils.cur_time(), end - start))
    print('==================================================')

def watchdog_entry():
    print("watchdog bark")
    os.kill(os.getpid(), signal.SIGTERM)

def timer_entry():
    print('=======================================')

    watchdog = Timer(30, watchdog_entry)
    watchdog.start()
    pull_once()
    watchdog.cancel()
    tr = Timer(utils.getNextTime(), timer_entry)
    tr.start()

if __name__=='__main__':
    tr = Timer(1, timer_entry)
    tr.start()

    wsServer = Server()
    wsServer.startServer()
